﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Text;
using FacebookWrapper;

namespace B13_Ex03_David_300512340_Alexey_321203689
{
    public class MainLogic
    {
        private const string k_ApplicationId = "167087790106782";
        private static MainLogic s_Instance = null;
        private UserWrapper m_LoggedInUser;
        private LoginResult m_Result;

        public bool IsLogedIn { get; set; }

        private MainLogic()
        {
        }

        public static MainLogic GetInstance()
        {
            if (s_Instance == null)
            {
                s_Instance = new MainLogic();
            }

            return s_Instance;
        } 

        public void Login()
        {
            m_Result = FacebookService.Login(k_ApplicationId, "user_status", "user_photos", "user_events", "friends_photos", "friends_events", "read_friendlists", "offline_access", "read_stream");
            if (string.IsNullOrEmpty(m_Result.ErrorMessage) && !string.IsNullOrEmpty(m_Result.AccessToken))
            {
                initUserWrapper();
                FacebookService.s_CollectionLimit = 0; // Get all the collection information.
                ApplicationSettings.Instance.AccessToken = m_Result.AccessToken;
                IsLogedIn = true;
            }
            else
            {
                failedToLogin();
            }
        }

        public void AutoLogIn()
        {
            m_Result = FacebookService.Connect(ApplicationSettings.Instance.AccessToken);
            if (string.IsNullOrEmpty(m_Result.ErrorMessage))
            {
                initUserWrapper();
                FacebookService.s_CollectionLimit = 0;
                IsLogedIn = true;
            }
            else
            {
                failedToLogin();
            }
        }

        internal UserWrapper LoggedInUser
        {
            get { return m_LoggedInUser; }
        }

        private void initUserWrapper()
        {
            m_LoggedInUser = new UserWrapper();
            m_LoggedInUser.UserInformation = m_Result.LoggedInUser;
        }

        private void failedToLogin()
        {
            IsLogedIn = false;
            MessageBox.Show(m_Result.ErrorMessage);
        }
    }
}
